#include "mydetegate.h"
#include <QComboBox>

MyDelegate::MyDelegate(int Col,const QStringList& labels,QObject *parent):
    QItemDelegate(parent),
    COMBOXCOL(Col),
    _labels(labels)
{

}

MyDelegate::~MyDelegate()
{

}

void MyDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
    const QModelIndex &index) const
{
    QItemDelegate::paint(painter, option, index);
}

QSize MyDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    return QItemDelegate::sizeHint(option, index);
}

QWidget *MyDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option,
                                                   const QModelIndex &index) const
{
    if (index.isValid() && index.column() == COMBOXCOL)
    {
        QComboBox *editor = new QComboBox(parent);
        editor->setEditable(true);
        editor->installEventFilter(const_cast<MyDelegate *>(this));
        return editor;
    }
    else
    {
        return QItemDelegate::createEditor(parent, option, index);
    }
}

void MyDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    if (index.isValid() && index.column() == COMBOXCOL)
    {
        QString value = index.model()->data(index, Qt::DisplayRole).toString();
        QComboBox *combox = static_cast<QComboBox *>(editor);
        for(int i=0;i<_labels.size();i++)
            combox->addItem(_labels[i],i);
        combox->setCurrentText(value);
    }
    else
    {
        QItemDelegate::setEditorData(editor, index);
    }
}

void MyDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                             const QModelIndex &index) const
{
    if (index.isValid() && index.column() == COMBOXCOL)
    {
        QComboBox *combox = static_cast<QComboBox *>(editor);
        model->setData(index, combox->currentText());
    }
    else
    {
        QItemDelegate::setModelData(editor, model, index);
    }
}

void MyDelegate::SetComboxItems(const QStringList &labels){
    this->_labels=labels;
}
